package org.datascooter.parser;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.datascooter.exception.DataScooterException;
import org.datascooter.inface.ISnipBuilder;
import org.datascooter.inface.ISnipBuilderProvider;
import org.datascooter.inface.IXMLReader;

public class DSBuilderProvider extends AbstractProvider<ISnipBuilder> implements ISnipBuilderProvider {

	private Map<String, String> builderMap = new HashMap<String, String>();

	public DSBuilderProvider(IXMLReader... readerArray) {
		super(readerArray);
	}

	@Override
	public ISnipBuilder getItem(String dname) {
		String className = builderMap.get(dname);
		if (className != null) {
			try {
				return (ISnipBuilder) Class.forName(className).getConstructor().newInstance();
			} catch (Exception e) {
				Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "***Not found class in a source:  " + className, e);
				throw new DataScooterException(e);
			}
		}
		return null;
	}

	@Override
	protected void processRoot(IXMLReader element) {
		try {
			ISnipBuilder builder = (ISnipBuilder) Class.forName(element.getAttribute("class")).getConstructor().newInstance();
			builderMap.put(builder.getContextId(), element.getAttribute("class"));
		} catch (Exception e) {
			Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "***Not found class in a source:  " + element.getNamespaceIdentifier(), e);
			throw new DataScooterException(e);
		}
	}
}
